package com.woniuxy.intellihome.controller.front;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.intellihome.entity.*;
import com.woniuxy.intellihome.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2021-08-11
 */
@Slf4j
@Controller("front/SPU")
@RequestMapping(value = "front/SPU", produces = "application/json")
public class GoodsSpuController {
    @Autowired
    private GoodsSpuService goodsSpuService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private SpecService specService;
    @Autowired
    private GoodsSpecDetailService goodsSpecDetailService;
    @Autowired
    private CartService cartService;
    @Autowired
    private DetailimgService detailimgService;
    @Autowired
    private VReviewService vReviewService;
    @Autowired
    private ReviewService reviewService;
    @Autowired
    private VgoodsService vgoodsService;
    @Autowired
    private UserService userService;

    /**
     * 首页根据商品类型展示
     */
    @GetMapping("index/{id}")
    public String list(@PathVariable int id, Model model, HttpSession session) {
        List<Category> category = categoryService.getByStatus();
        List<Sku> goodsNews = skuService.getNew();
        List<Sku> goodsHots = skuService.getHot();
        List<Sku> goodsNew = new ArrayList<>();
        List<Sku> goodsHot = new ArrayList<>();
        for (Sku good : goodsNews) {
            if (good.getSpu().getCategoryId() == id) {
                goodsNew.add(good);
            }
        }
        for (Sku good : goodsHots) {
            if (good.getSpu().getCategoryId() == id) {
                goodsHot.add(good);
            }
        }
        User user = (User) session.getAttribute("user1");
        model.addAttribute("user", user);
        model.addAttribute("goodsNew", goodsNew);
        model.addAttribute("goodsHot", goodsHot);
        model.addAttribute("category", category);
        return "index";
    }

    /**
     * 首页展示
     */
    @GetMapping("index")
    public String list(Model model, HttpSession session) {
        List<Category> category = categoryService.getByStatus();
        List<Sku> goodsNews = skuService.getNew();
        List<Sku> goodsHots = skuService.getHot();
        System.out.println(goodsNews);
        User user = (User) session.getAttribute("user1");
        model.addAttribute("user", user);
        model.addAttribute("goodsNew", goodsNews);
        model.addAttribute("goodsHot", goodsHots);
        model.addAttribute("category", category);
        return "index";
    }


    /**
     * 商品分页展示，根据条件搜索
     */
    @GetMapping("lists")
    public String list(Integer current, Integer pageSize, GoodsSpu goodsSpu, Model model, HttpSession session) {
        if (current == null) {
            current = 1;
        }
        if (pageSize == null) {
            pageSize = 1;
        }
        QueryWrapper<GoodsSpu> queryWrapper = new QueryWrapper<>();
        if (goodsSpu.getName() != null && goodsSpu.getName().trim().length() != 0) {
            queryWrapper.like("name", goodsSpu.getName());
        }
        if (goodsSpu.getCategoryId() != null && goodsSpu.getCategoryId() != 0) {
            queryWrapper.eq("category_id", goodsSpu.getCategoryId());
        }
        if (goodsSpu.getStartTime() != null && goodsSpu.getStartTime().trim().length() != 0) {
            queryWrapper.ge("up_time", goodsSpu.getStartTime());
        }
        if (goodsSpu.getEndTime() != null && goodsSpu.getEndTime().trim().length() != 0) {
            queryWrapper.le("up_time", goodsSpu.getEndTime());
        }
        if (goodsSpu.getIshot() != null) {
            queryWrapper.eq("ishot", "y");
        }
        if (goodsSpu.getIsnew() != null) {
            queryWrapper.eq("isnew", "y");
        }

        Page<GoodsSpu> page = new Page<>(current, pageSize);
        page = goodsSpuService.page(page, queryWrapper);
        List<Sku> skus = new ArrayList();
        for (GoodsSpu good : page.getRecords()) {
            List<Sku> sku = skuService.getAllSkuBelong2Spu(good.getId());
            if (sku != null && !sku.isEmpty()) {
                skus.add(sku.get(0));
            }
        }
        User user = (User) session.getAttribute("user1");
        model.addAttribute("user", user);
        model.addAttribute("page", page);
        model.addAttribute("skus", skus);
        model.addAttribute("goodsSpu", goodsSpu);
        model.addAttribute("category", categoryService.list());
//        log.debug("page.record:",vGoodsService.page(page, queryWrapper).getRecords().get(0));
        return "Product_List";
    }

    @GetMapping("view/{id}")
    public String view(@PathVariable int id, Model model, HttpSession session) {
        List<Sku> skus = skuService.getAllSkuBelong2Spu(id);
        GoodsSpu goodsSpu = goodsSpuService.getById(id);
        List<Spec> specs = specService.getByGoodsId(id);
        List<Category> category = categoryService.getByStatus();
        List<Detailimg> detailimgList = new ArrayList<>();
        for (Sku s : skus) {
            List<Detailimg> detailimgs = detailimgService.getBySkuId(s.getId());
            detailimgList.addAll(detailimgs);
        }
        List<Sku> goodsNews = skuService.getNew();
        List<Sku> goodsNew = new ArrayList<>();
        for (Sku good : goodsNews) {
            if (good.getSpu().getId() != id) {
                goodsNew.add(good);
            }
        }
        model.addAttribute("spuId", id);
        model.addAttribute("goodsNew", goodsNew);
        model.addAttribute("imgs", detailimgList);
        User user = (User) session.getAttribute("user1");
        model.addAttribute("goods", goodsSpu);
        model.addAttribute("skus", skus);
        model.addAttribute("specs", specs);
        model.addAttribute("user", user);
        model.addAttribute("category", category);
        return "Product_detailed";
    }

    @GetMapping("getPrice")
    @ResponseBody
    public ResponseEntity getPrice(@RequestParam String ids) {
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setMsg("查询成功");
        responseEntity.setCode(ResponseState.SUCCESS);
        String[] split = ids.split(",");
        Integer i = 0;
        if (split.length == 2) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId2(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
        } else if (split.length == 3) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId3(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
        } else if (split.length == 4) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId4(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]));
        } else if (split.length == 5) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId5(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]), Integer.parseInt(split[4]));
        }
        if (i == null) {
            responseEntity.setMsg("查询成功");
            responseEntity.setCode(500);
            return responseEntity;
        }
        BigDecimal price = skuService.getPriceById(i);
        responseEntity.setData(price);
        return responseEntity;
    }

    @GetMapping("getSales")
    @ResponseBody
    public ResponseEntity getSales(@RequestParam String ids) {
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setMsg("查询成功");
        responseEntity.setCode(ResponseState.SUCCESS);
        String[] split = ids.split(",");
        Integer i = 0;
        if (split.length == 2) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId2(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
        } else if (split.length == 3) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId3(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
        } else if (split.length == 4) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId4(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]));
        } else if (split.length == 5) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId5(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]), Integer.parseInt(split[4]));
        }
        if (i == null) {
            responseEntity.setMsg("查询成功");
            responseEntity.setCode(500);
            return responseEntity;
        }
        int sales = skuService.getSalesById(i);
        responseEntity.setData(sales);
        return responseEntity;
    }

    @GetMapping("getSkuId")
    @ResponseBody
    public ResponseEntity getSkuId(@RequestParam String ids) {
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setMsg("查询成功");
        responseEntity.setCode(ResponseState.SUCCESS);
        String[] split = ids.split(",");
        Integer i = 0;
        if (split.length == 2) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId2(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
        } else if (split.length == 3) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId3(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]));
        } else if (split.length == 4) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId4(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]));
        } else if (split.length == 5) {
            i = goodsSpecDetailService.getSpecIdBySpecValueId5(Integer.parseInt(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), Integer.parseInt(split[3]), Integer.parseInt(split[4]));
        }
        if (i == null) {
            responseEntity.setMsg("查询成功");
            responseEntity.setCode(500);
            return responseEntity;
        }
        responseEntity.setData(i);
        return responseEntity;
    }

    @PostMapping("addToCart")
    @ResponseBody
    public ResponseEntity addToCart(Cart cart) {
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setMsg("查询成功");
        responseEntity.setCode(ResponseState.SUCCESS);
        responseEntity.setData(cart);
        cart.setIschoose("y");
        cartService.add(cart);

        return responseEntity;
    }

    @PostMapping("addOrder")
    @ResponseBody
    public ResponseEntity addOrder(Cart cart) {
        ResponseEntity responseEntity = new ResponseEntity();
        responseEntity.setMsg("查询成功");
        responseEntity.setCode(ResponseState.SUCCESS);
        cart.setSku(skuService.getWithSpuSpecDetailBySKUId(cart.getSkuId()));
        cart.setIschoose("y");
        List<Cart> carts = new ArrayList<>();
        carts.add(cart);
        responseEntity.setData(carts);
        return responseEntity;
    }

    @ResponseBody
    @PostMapping("review")
    public ResponseEntity getAllreview(Review review) {
        ResponseEntity responseEntity = new ResponseEntity();
//        System.out.println(vReview);
//        List<VReview> vReviews = vReviewService.getAllReviewBySpuIdAndType(vReview.getSpuId(), vReview.getType());
//        List<VReview> vReviews0 = vReviewService.getAllReviewBySpuId(vReview.getSpuId());
//        List<Integer> skuIds1 = goodsSpecDetailService.getSkuIdBySpuId(vReview.getSpuId());
        List<Integer> skuIds1 = goodsSpecDetailService.getSkuIdBySpuId(review.getSpuId());
//        List<Integer> skuIds = new ArrayList<>();
//        skuIds.addAll(skuIds1);
        for (int i = 0; i < skuIds1.size(); i++) {
            for (int j = 0; j < skuIds1.size(); j++) {
                if (i != j && skuIds1.get(i).equals(skuIds1.get(j))) {
                    skuIds1.remove(skuIds1.get(j));
                }
            }
        }
        List<Review> reviews = new ArrayList<>();
        for (int i : skuIds1) {
            reviews.addAll(reviewService.getBySkuid(i));
        }
        for (Review r : reviews) {
            r.setUser(userService.getById(r.getUserId()));
            r.setUserAccount(userService.getAccountById(r.getUserId()));
            List<VGoods> vGoodses = vgoodsService.getDetailById(r.getSkuId());
            List<String> names = new ArrayList<>();
            for (VGoods vGoods : vGoodses) {
                names.add(vGoods.getName());
            }
            for (int i = 0; i < names.size(); i++) {
                for (int j = 0; j < names.size(); j++) {
                    if (i != j && names.get(i).equals(names.get(j))) {
                        names.remove(names.get(j));
                    }
                }
            }
            String goodsName = names.get(0);
            r.setGoodsName(goodsName);
            r.setSpecValues(vgoodsService.getAllSpecValues(r.getSkuId()));
            r.setVGoodses(vGoodses);
        }


        List<Review> reviewsByType = new ArrayList<>();
//        if (vReview.getType().equals("0")) {
//            //就查询该商品的所有评论
//            for (VReview vr : vReviews0
//            ) {
//                vReviewsByType.add(vr);
//
//            }

//        return responseEntity;
//    }
        System.out.println(review.getSpuId() + "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        if (review.getType().equals("1")) {
            //好评
            for (Review r : reviews) {
                if (r.getType().equals("1")) {
                    reviewsByType.add(r);
                }
            }
            responseEntity.setCode(201);
            responseEntity.setMsg("查询该商品的所有好评评论");
            responseEntity.setData(reviewsByType);
            for (Review r : reviewsByType) {
                System.out.println(r.toString());
            }
            return responseEntity;
        }
        if (review.getType().equals("2")) {
            //中评
            for (Review r : reviews) {
                if (r.getType().equals("2")) {
                    reviewsByType.add(r);
                }
            }
            responseEntity.setCode(202);
            responseEntity.setMsg("查询该商品的所有中评论");
            responseEntity.setData(reviewsByType);
            return responseEntity;
        }
        if (review.getType().equals("3")) {
            //中评
            for (Review r : reviews) {
                if (r.getType().equals("3")) {
                    reviewsByType.add(r);
                }
            }
            responseEntity.setCode(202);
            responseEntity.setMsg("查询该商品的所有中评论");
            responseEntity.setData(reviewsByType);
            return responseEntity;
        }
        responseEntity.setCode(200);
        responseEntity.setMsg("查询该商品的所有评论");
        responseEntity.setData(reviews);
        return responseEntity;
    }
}

